/*
 * @Date: 2023-02-15 15:55:30
 * @LastEditTime: 2023-09-07 16:32:10
 * @FilePath: /wkw/src/api/index.ts
 * 介绍:
 */
import type { AxiosRequestConfig } from "axios";
import Request, { RequestConfig } from "@@/utils/tools/Request";
import useSysStore from "@@/store/useSysStore";
import useUserinfoStore from "@@/store/useUserinfoStore";
import { filterObject } from "@@/utils/tools/object";
import { toast } from "@@/hooks/vantHooks";

const env = import.meta.env;

const defaHttp: InstanceType<typeof Request> = new Request(
  {},
  {
    filterReq: filterObject,
    hidLoading() {
      toast.close();
    },
    isSuccess(res: any) {
      return {
        success: res.code === 200,
        message: res.msg,
      };
    },
    showFail(message) {
      toast.error(message);
    },
    showLoading(message) {
      toast.loading(message);
    },
    showSuccess(message) {
      toast.success(message);
    },
  }
);
let baseURL: string;
if (env.VITE_PROXY == "1") {
  baseURL = env.VITE_API_PREFIX; //配置默认请求地址--跨域代理
} else {
  baseURL = env.VITE_BASE_URL + env.VITE_API_PREFIX; //配置默认请求地址--无代理
}
defaHttp.axios.defaults.baseURL = baseURL;
defaHttp.axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";
defaHttp.axios.interceptors.request.use(<any>((
  config: RequestConfig
): AxiosRequestConfig => {
  /**token */
  return { ...config, headers: getHeaderCfg() };
}));

export function getHeaderCfg(oldHeaders?: AnyObject): AnyObject {
  const userinfo = useUserinfoStore();
  const sysStore = useSysStore();
  const authorization = `Bearer ${userinfo.tokenInfo?.access_token}`;
  let headers: AnyObject = { ...oldHeaders, authorization };
  if (sysStore.reqHeader) headers = { ...headers, ...sysStore.reqHeader };
  return headers;
}

export { defaHttp, baseURL };

export namespace Api {
  export interface Res<D = any> {
    code: number;
    msg: string;
    status: boolean;
    data: D;
  }
}
/**分页接口 */
export namespace PagingApi {
  /**请求分页接口返res类型 */
  export type Res<T extends any[] = any[]> = Api.Res<Data<T>>;
  /**分页data类型 */
  export interface Data<T> {
    /**当前页码数 */
    current_page: number;
    data: T;
    /**第一页URL */
    first_page_url: string;
    /**首页 */
    from: number;
    /**尾页 */
    last_page: number;
    /**尾页URL */
    last_page_url: string;
    links: Array<{
      url: string | null;
      label: string;
      active: boolean;
    }>;
    /**下一页url */
    next_page_url: string;
    path: string;
    /**每页数据长度 */
    per_page: number;
    prev_page_url: string;
    /**下一页 */
    to: number;
    /**总数 */
    total: number;
  }

  /**分页参数 */
  export interface Req {
    page: number;
  }
}
